//----------------------------------------------------------
// 多生产多消费日志系统使用示例
// 演示如何在高并发场景下使用多生产多消费日志系统
//----------------------------------------------------------

#include "../src/multi_ymbxlog.hpp"
#include <thread>
#include <vector>
#include <chrono>
#include <iostream>

using namespace ymbxlog;

// 生产者线程函数
void ProducerThread(MultiLogger::ptr logger, int thread_id, int message_count)
{
    for (int i = 0; i < message_count; ++i) {
        MULTI_LOG_INFO(logger, "Thread ", thread_id, " producing message ", i);
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    MULTI_LOG_INFO(logger, "Thread ", thread_id, " finished producing messages");
}

// 模拟高并发场景
void HighConcurrencyTest()
{
    std::cout << "=== 高并发多生产多消费日志测试 ===" << std::endl;
    
    // 创建一个多生产多消费日志器，支持4个消费者线程
    auto logger = CreateMultiLoggerWithMultipleSinks(
        "high_concurrency_logger",
        {"logs/concurrent_test.log", "logs/concurrent_test2.log"},
        true,  // 启用控制台输出
        "%d{%Y-%m-%d %H:%M:%S} [%t] %N [%l] %F:%L %M",
        LogLevel::Level::DEBUG,
        4  // 4个消费者线程
    );
    
    // 启动日志器
    logger->Start();
    
    const int producer_count = 8;  // 8个生产者线程
    const int messages_per_thread = 100;  // 每个线程产生100条消息
    
    std::vector<std::thread> producers;
    
    // 启动生产者线程
    auto start_time = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < producer_count; ++i) {
        producers.emplace_back(ProducerThread, logger, i, messages_per_thread);
    }
    
    // 等待所有生产者线程完成
    for (auto& thread : producers) {
        thread.join();
    }
    
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
    
    std::cout << "所有生产者线程完成，耗时: " << duration.count() << "ms" << std::endl;
    
    // 停止日志器并等待所有消费者线程完成
    logger->Stop();
    logger->Wait();
    
    std::cout << "日志处理完成" << std::endl;
}

// 测试不同类型的Sink
void DifferentSinksTest()
{
    std::cout << "\n=== 不同Sink类型测试 ===" << std::endl;
    
    // 1. 控制台输出
    auto console_logger = CreateMultiLoggerWithStdout(
        "console_logger",
        "%d{%Y-%m-%d %H:%M:%S} [%t] %N [%l] %F:%L %M",
        LogLevel::Level::INFO,
        2
    );
    
    // 2. 文件输出
    auto file_logger = CreateMultiLoggerWithFile(
        "file_logger",
        "logs/file_test.log",
        "%d{%Y-%m-%d %H:%M:%S} [%t] %N [%l] %F:%L %M",
        LogLevel::Level::DEBUG,
        2
    );
    
    // 3. 滚动文件输出（基于大小）
    auto roll_file_logger = CreateMultiLoggerWithRollFile(
        "roll_file_logger",
        "logs/roll_test",
        1024,  // 1KB大小限制
        "%d{%Y-%m-%d %H:%M:%S} [%t] %N [%l] %F:%L %M",
        LogLevel::Level::DEBUG,
        2
    );
    
    // 4. 时间滚动文件输出
    auto time_roll_logger = CreateMultiLoggerWithTimeRollFile(
        "time_roll_logger",
        "logs/time_roll_test",
        TimeSep::Minute,  // 每分钟滚动一次
        "%d{%Y-%m-%d %H:%M:%S} [%t] %N [%l] %F:%L %M",
        LogLevel::Level::DEBUG,
        2
    );
    
    // 启动所有日志器
    console_logger->Start();
    file_logger->Start();
    roll_file_logger->Start();
    time_roll_logger->Start();
    
    // 产生一些测试日志
    for (int i = 0; i < 50; ++i) {
        MULTI_LOG_INFO(console_logger, "Console message ", i);
        MULTI_LOG_DEBUG(file_logger, "File message ", i);
        MULTI_LOG_WARN(roll_file_logger, "Roll file message ", i);
        MULTI_LOG_ERROR(time_roll_logger, "Time roll message ", i);
        
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    
    // 停止所有日志器
    console_logger->Stop();
    file_logger->Stop();
    roll_file_logger->Stop();
    time_roll_logger->Stop();
    
    // 等待完成
    console_logger->Wait();
    file_logger->Wait();
    roll_file_logger->Wait();
    time_roll_logger->Wait();
    
    std::cout << "不同Sink类型测试完成" << std::endl;
}

// 测试日志器管理器
void LoggerManagerTest()
{
    std::cout << "\n=== 日志器管理器测试 ===" << std::endl;
    
    // 创建多个日志器
    auto logger1 = CreateMultiLoggerWithStdout("manager_test1", "", LogLevel::Level::DEBUG, 2);
    auto logger2 = CreateMultiLoggerWithFile("manager_test2", "logs/manager_test2.log", "", LogLevel::Level::INFO, 2);
    auto logger3 = CreateMultiLoggerWithRollFile("manager_test3", "logs/manager_test3", 512, "", LogLevel::Level::WARNING, 2);
    
    // 启动所有日志器
    StartAllMultiLoggers();
    
    // 从管理器获取日志器
    auto retrieved_logger1 = GetMultiLogger("manager_test1");
    auto retrieved_logger2 = GetMultiLogger("manager_test2");
    auto retrieved_logger3 = GetMultiLogger("manager_test3");
    
    // 使用获取的日志器
    for (int i = 0; i < 20; ++i) {
        MULTI_LOG_DEBUG(retrieved_logger1, "Manager test 1 message ", i);
        MULTI_LOG_INFO(retrieved_logger2, "Manager test 2 message ", i);
        MULTI_LOG_WARN(retrieved_logger3, "Manager test 3 message ", i);
        
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
    
    // 停止所有日志器
    StopAllMultiLoggers();
    WaitAllMultiLoggers();
    
    std::cout << "日志器管理器测试完成" << std::endl;
}

// 性能对比测试
void PerformanceComparisonTest()
{
    std::cout << "\n=== 性能对比测试 ===" << std::endl;
    
    const int message_count = 10000;
    const int thread_count = 4;
    
    // 测试多生产多消费日志器
    auto multi_logger = CreateMultiLoggerWithFile(
        "performance_test",
        "logs/performance_test.log",
        "",
        LogLevel::Level::INFO,
        4  // 4个消费者线程
    );
    
    multi_logger->Start();
    
    std::vector<std::thread> threads;
    auto start_time = std::chrono::high_resolution_clock::now();
    
    // 启动多个生产者线程
    for (int i = 0; i < thread_count; ++i) {
        threads.emplace_back([multi_logger, i, message_count]() {
            for (int j = 0; j < message_count; ++j) {
                MULTI_LOG_INFO(multi_logger, "Performance test message from thread ", i, " message ", j);
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
    
    std::cout << "多生产多消费日志器性能测试:" << std::endl;
    std::cout << "  总消息数: " << (message_count * thread_count) << std::endl;
    std::cout << "  总耗时: " << duration.count() << "ms" << std::endl;
    std::cout << "  平均每秒处理消息数: " << (message_count * thread_count * 1000.0 / duration.count()) << std::endl;
    
    multi_logger->Stop();
    multi_logger->Wait();
}

int main()
{
    std::cout << "多生产多消费日志系统示例程序" << std::endl;
    std::cout << "================================" << std::endl;
    
    try {
        // 运行各种测试
        HighConcurrencyTest();
        DifferentSinksTest();
        LoggerManagerTest();
        PerformanceComparisonTest();
        
        std::cout << "\n所有测试完成！" << std::endl;
        
    } catch (const std::exception& e) {
        std::cerr << "测试过程中发生异常: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
} 